﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.Interfaces;
using JuCheap.Core.Models.Filters;
using JuCheap.Core.Models.ViewModels;
using JuCheap.Core.Web.Filters;
using JuCheap.Core.Web.Models;
using Microsoft.AspNetCore.Mvc;


namespace JuCheap.Core.Web.Controllers
{
    public class DepartmentGroupController : Controller
    {
        private readonly IRepository _iRepository;
        public DepartmentGroupController(IRepository iRepository)
        {
            _iRepository = iRepository;
        }
        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> Delete([FromBody]List<string> ids)
        {
            var result = new JsonResultModel<bool>();
            if (ids.AnyOne())
            {
                result.flag = true;

                foreach (string str in ids)
                {
                    DepartmentGroupFilter df = new DepartmentGroupFilter();
                    df.id = int.Parse(str);
                    var dto = await _iRepository.GetDepartmentGroupWoker(int.Parse(str));
                    if (dto.WorkerId !=0)
                    {
                        WorkerFilter wf = new WorkerFilter();
                        wf.id = dto.WorkerId;

                        var worker = await _iRepository.GetWorkers(wf);
                        var row = worker.rows.Where(r => r.Status == 1);
                        if (!row.AnyOne())
                        {
                            await _iRepository.DeleteDepartmentGroup(Convert.ToInt32(str));
                        }
                        else
                        {
                            result.msg = "本组下有未离场人员!";
                            result.flag = false;
                            break;
                        }
                    }
                    
                }
            }
            return Json(result);
        }
        /// <summary>
        /// 搜索页面
        /// </summary>
        /// <param name="filters">查询参数</param>
        /// <returns></returns>
        [IgnoreRightFilter]
        public async Task<IActionResult> GetListWithPager(DepartmentGroupFilter filters)
        {
            var result = await _iRepository.GetDepartmentGroups(filters);
            foreach(var r in result.rows)
            {

                //r.DevicesText = string.Join(",", r.Devices.Select(w => w.Name).ToArray());
                //r.WorkersText = string.Join(",", r.Workers.Select(w => w.Name).ToArray());
            }
            //var depts = new
            //{
            //    results = result.rows.Select(x => new { id = x.Id,
            //        name = x.Name,
            //        week =  x.OpenCycle,
            //        hardware = string.Join(",", x.Devices.Select(w => w.Name).ToArray()),
            //        worker = string.Join(",", x.Workers.Select(w => w.Name).ToArray()),
            //    })
            //};
            return Json(result);
        }

        public async Task<IActionResult> GetDepartmentGroups(string q)
        {
            var filter = new DepartmentGroupFilter
            {
                page = 1,
                rows = 1000,
                keywords = ""
            };
            var result = await _iRepository.GetDepartmentGroups(filter);
            var depts = new
            {
                results = result.rows.Select(x => new { id = x.Id, text = x.Name })
            };
            return Json(depts);
        }


        public IActionResult Add()
        {
            return View(new DepartmentGroupViewModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Add(DepartmentGroupViewModel model)
        {
            if (ModelState.IsValid)
            {
                var dto = await _iRepository.GetDepartmentGroups(new DepartmentGroupFilter() { name = model.Name, });
                if (dto == null || dto.rows.Count == 0)
                {
                    //model.Devices = model.DevicesId.Split(',').ToList().Select(d => new HardWareDeviceViewModel() { Id= Convert.ToInt32(d) }).ToList();
                    //model.Workers = model.WorkersId.Split(',').ToList().Select(d => new WorkerViewModel() { Id = Convert.ToInt32(d) }).ToList();
                    var result = await _iRepository.AddDepartmentGroup(model);
                    //if (result.IsNotBlank())
                    return RedirectToAction("Index");
                }                
                else
                {
                    ModelState.AddModelError(nameof(model.Name), "名称重复");
                }
            }
            return View(model);
        }



        public async Task<IActionResult> Edit(int id)
        {
            var dto = await _iRepository.GetDepartmentGroups(new DepartmentGroupFilter() { id = id, });

            if (dto == null || dto.rows.Count == 0)
            {
              
                return RedirectToAction("Add");
            }
            //dto.rows[0].DevicesId = string.Join(",", dto.rows[0].Devices.Select(w => w.Id).ToArray());
            //dto.rows[0].WorkersId = string.Join(",", dto.rows[0].Workers.Select(w => w.Id).ToArray());
            return View(dto.rows[0]);
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(DepartmentGroupViewModel model)
        {
            if (ModelState.IsValid)
            {
                //model.Devices = model.DevicesId.Split(',').ToList().Select(d => new HardWareDeviceViewModel() { Id = Convert.ToInt32(d) }).ToList();
                //model.Workers = model.WorkersId.Split(',').ToList().Select(d => new WorkerViewModel() { Id = Convert.ToInt32(d) }).ToList();
                var result = await _iRepository.UpdateDepartmentGroup(model);
                return RedirectToAction("Index");
            }
            return View(model);
        }
    }
}